package com.buba.appointment.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buba.appointment.data.vo.NucleicAcidAppointmentEchoVo;
import com.buba.appointment.data.vo.Times;
import com.buba.appointment.service.NucleicAcidAppointmentService;
import com.buba.appointment.service.impl.NucleicAcidAppointmentServiceImpl;
import com.buba.pojo.appointment.NucleicAcidAppointment;
import com.buba.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  核酸预约时间段
 * </p>
 *
 * @author xhh
 * @since 2022-06-13
 */
@EnableScheduling
@RestController
@RequestMapping("/appointment/nucleic-acid-appointment")
public class NucleicAcidAppointmentController {
    @Autowired
    private NucleicAcidAppointmentService naaService;
    @Autowired
    //@Qualifier("hisDataRedisTemplate")
    private RedisTemplate redisTemplate;
    //生成的上下午的时间段数目
    public static Integer number=6;
    //生成的每个时间段的号源数
    public static Integer numberSource=10;
    /**
    * todo 核酸预约回显
    * @param 
    * @return com.buba.utils.R
    * @author xhh
    * @data 2022/6/13 20:26
    */
    @RequestMapping(value = "/nucleicAcidEcho",method = RequestMethod.POST)
    public R nucleicAcidEcho() {
        List<NucleicAcidAppointmentEchoVo> list=new ArrayList<>();
        TreeMap<String, Set<LinkedHashMap>> map = test(0);
        try {

            for (String key : map.keySet()) {
                LocalDate localDate = LocalDate.parse(key, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                NucleicAcidAppointmentEchoVo vo = new NucleicAcidAppointmentEchoVo();
                vo.setDay(localDate.getDayOfMonth());
                vo.setTime(localDate);
                vo.setWeek(localDate.getDayOfWeek().getValue());

                List<Times> times = new ArrayList<>();
                for (LinkedHashMap linkedHashMap : map.get(key)) {
                    for (Object o : linkedHashMap.keySet()) {
                        //o就是时间 o1就是号源
                        Object o1 = linkedHashMap.get(o);
                        LocalTime l = LocalTime.parse(o.toString(), DateTimeFormatter.ofPattern("HH:mm"));
                        Integer i = Integer.parseInt(o1.toString());
                        String apm=l.getHour()<=12?"am":"pm";
                        Times t = new Times(l, i,apm);
                        times.add(t);
                    }
                }
                vo.setTimesList(times);
                list.add(vo);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }

        if(list.size()>0 && map!=null){
            //System.out.println(list);
            //System.err.println(R.ok().data("data",list));
            return R.ok().data("data",list);
        }
        else{
            return R.error();
        }
    }



    /**
    * todo 刷新更新redis中号源数到mysql中
    * @param 
    * @return void
    * @author xhh
    * @data 202z2/6/14 15:05
    */
    @RequestMapping("/refresh")
    public void refresh() {
        LocalDate localDate=LocalDate.now();
        LocalDate localDateFlag=localDate;
        Map<String, Set<LinkedHashMap>> test = test(0);
        for (Set<LinkedHashMap> value : test.values()) {
            for(LinkedHashMap map:value){
                for (Object o : map.keySet()) {
                    QueryWrapper queryWrapper=new QueryWrapper();
                    LocalDate localDate1=localDateFlag;
                    LocalTime localTime=LocalTime.parse(o.toString(),DateTimeFormatter.ofPattern("HH:mm"));
                    Integer numberSource = Integer.parseInt(map.get(o).toString());
                    queryWrapper.eq("date",localDate1);
                    queryWrapper.eq("starte_time",localTime);
                    NucleicAcidAppointment appointment=new NucleicAcidAppointment();
                    appointment.setNumberSource(numberSource);
                    naaService.update(appointment,queryWrapper);
                }
            }
            localDateFlag=localDateFlag.plusDays(1);
        }
    }
    /**
    * todo 生成一周的数据
    * @param
    * @return boolean
    * @author xhh
    * @data 2022/6/13 21:08
    */
    @RequestMapping(value = "/generateOneWeekDate")
    public boolean generateOneWeekDate() {
        List<LocalDate> nowWeek = new NucleicAcidAppointmentServiceImpl().getNowWeek();
        List<NucleicAcidAppointment> list=new ArrayList<>(99);
        LocalTime localTimeAm;
        LocalTime localTimePm;
        for (LocalDate localDate : nowWeek) {
            int datePoint=localDate.getMonthValue()*100+ localDate.getDayOfMonth();
            ZSetOperations zSetOperations = redisTemplate.opsForZSet();
            //zSetOperations.add(localDate.toString(),null,datePoint);
            localTimeAm=LocalTime.parse("08:00",DateTimeFormatter.ofPattern("HH:mm"));
            localTimePm=LocalTime.parse("13:00",DateTimeFormatter.ofPattern("HH:mm"));
            int week=localDate.getDayOfWeek().getValue();
            for(int i=1;i<=number;i++){
                int timePoint=localTimeAm.getHour()*100+localTimeAm.getMinute();
                LinkedHashMap hashMap=new LinkedHashMap();
                hashMap.put(localTimeAm.toString(),numberSource);
                zSetOperations.add(localDate.toString(),hashMap,timePoint);

                NucleicAcidAppointment appointment=new NucleicAcidAppointment();
                appointment.setApm("am");
                appointment.setWeek(week);
                appointment.setNumberSource(numberSource);
                appointment.setDate(localDate);
                appointment.setStarteTime(localTimeAm);
                localTimeAm = localTimeAm.plusMinutes(30);
                appointment.setEndTime(localTimeAm);
                list.add(appointment);
            }
            for(int i=1;i<=number;i++){
                int timePoint=localTimePm.getHour()*100+localTimePm.getMinute();
                LinkedHashMap hashMap=new LinkedHashMap();
                hashMap.put(localTimePm.toString(),numberSource);
                zSetOperations.add(localDate.toString(),hashMap,timePoint);

                NucleicAcidAppointment appointment=new NucleicAcidAppointment();
                appointment.setApm("pm");
                appointment.setWeek(week);
                appointment.setNumberSource(numberSource);
                appointment.setDate(localDate);
                appointment.setStarteTime(localTimePm);
                localTimePm = localTimePm.plusMinutes(30);
                appointment.setEndTime(localTimePm);
                list.add(appointment);
            }
        }
        boolean saveBatch = naaService.saveBatch(list);
        if(saveBatch) {
            return true;
        }
        else{
            return false;
        }

    }


    /**
    * todo 从redis中获取一周的预约时间段和号源的数据 参数 0 表示当天  1表示昨天
    * @param day
    * @return java.util.Map<java.lang.String,java.util.Set<java.util.LinkedHashMap>>
    * @author xhh
    * @data 2022/6/14 15:33
    */
    public TreeMap<String,Set<LinkedHashMap>> test(int day){
        TreeMap<String,Set<LinkedHashMap>> map=new TreeMap<String,Set<LinkedHashMap>>();
        LocalDate localDateNow = LocalDate.now().minusDays(day);
        for(int i=1;i<=7;i++){
            Set<LinkedHashMap> set = redisTemplate.opsForZSet().rangeByScore(localDateNow.toString(), 0, 2400);

            map.put(localDateNow.toString(),set);

            localDateNow=localDateNow.plusDays(1);
        }
        //for(String key:map.keySet()){
        //    Set<LinkedHashMap> set=map.get(key);
        //    System.err.println(key+"-----"+set);
        //}

        return map;
    }
    /**
     * todo 定时器,向NucleicAcidAppointment表添加数据 ，每天 00：00：5 执行
     * @param
     * @return void
     * @author xhh
     * @data 2022/6/13 21:06
     */
    @Scheduled(cron = "5 0 0  * * ?")
    public void myTask() {
        //当天日期
        LocalDate localDate=LocalDate.now();
        //获取昨天的日期
        LocalDate localDateBeforeDay=localDate.minusDays(1);
        //七天后的日期
        LocalDate localDateAfterWeek=localDateBeforeDay.plusWeeks(1);

        /*=====================================redis数据更新到mysql中=====================================*/
        //mysql同步redis中的数据，同步的是昨天的数据，将redis中昨天以及连带其他六天一共七天的数据
        //比如 今天 凌晨0点0分10秒  他会将昨天的redis中的数据变更到mysql中
        LocalDate localDateFlag=localDateBeforeDay;
        Map<String, Set<LinkedHashMap>> test = test(1);
        for (Set<LinkedHashMap> value : test.values()) {
            for(LinkedHashMap map:value){
                for (Object o : map.keySet()) {
                    QueryWrapper queryWrapper=new QueryWrapper();
                    LocalDate localDate1=localDateFlag;
                    LocalTime localTime=LocalTime.parse(o.toString(),DateTimeFormatter.ofPattern("HH:mm"));
                    Integer numberSource = Integer.parseInt(map.get(o).toString());
                    queryWrapper.eq("date",localDate1);
                    queryWrapper.eq("starte_time",localTime);
                    NucleicAcidAppointment appointment=new NucleicAcidAppointment();
                    appointment.setNumberSource(numberSource);
                    naaService.update(appointment,queryWrapper);
                }
            }
            localDateFlag=localDateFlag.plusDays(1);
        }
        //新的一天删除昨天的数据
        redisTemplate.delete(localDateBeforeDay.toString());
        /*=====================================redis,mysql新增数据=====================================*/
        LocalTime localTimeAm=LocalTime.parse("08:00",DateTimeFormatter.ofPattern("HH:mm"));
        LocalTime localTimePm=LocalTime.parse("13:00",DateTimeFormatter.ofPattern("HH:mm"));
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        for(int i=1;i<=number;i++){
            int timePoint=localTimeAm.getHour()*100+localTimeAm.getMinute();
            LinkedHashMap hashMap=new LinkedHashMap();
            hashMap.put(localTimeAm.toString(),numberSource);
            zSetOperations.add(localDateAfterWeek.toString(),hashMap,timePoint);

            NucleicAcidAppointment appointment=new NucleicAcidAppointment();
            appointment.setApm("am");
            appointment.setWeek(localDateAfterWeek.getDayOfWeek().getValue());
            appointment.setNumberSource(numberSource);
            appointment.setDate(localDateAfterWeek);
            appointment.setStarteTime(localTimeAm);
            localTimeAm = localTimeAm.plusMinutes(30);
            appointment.setEndTime(localTimeAm);
            boolean save = naaService.save(appointment);
        }
        for(int i=1;i<=number;i++){
            int timePoint=localTimePm.getHour()*100+localTimePm.getMinute();
            LinkedHashMap hashMap=new LinkedHashMap();
            hashMap.put(localTimePm.toString(),numberSource);
            zSetOperations.add(localDateAfterWeek.toString(),hashMap,timePoint);

            NucleicAcidAppointment appointment=new NucleicAcidAppointment();
            appointment.setApm("pm");
            appointment.setWeek(localDateAfterWeek.getDayOfWeek().getValue());
            appointment.setNumberSource(numberSource);
            appointment.setDate(localDateAfterWeek);
            appointment.setStarteTime(localTimePm);
            localTimePm = localTimePm.plusMinutes(30);
            appointment.setEndTime(localTimePm);
            boolean save = naaService.save(appointment);
        }
    }

    //@RequestMapping("test9")
    //public Integer updateRedisSet(){
    //    LinkedHashMap map=new LinkedHashMap();
    //    int source=2;
    //    Set<LinkedHashMap> set = redisTemplate.opsForZSet().rangeByScore(LocalDate.now().toString(), 800, 800);
    //    for (LinkedHashMap linkedHashMap : set) {
    //        for (Object o : linkedHashMap.keySet()) {
    //            Object o1 = linkedHashMap.get(o);
    //            System.out.println(Integer.parseInt(o1.toString()));
    //        }
    //    }
    //    map.put("08:00",1);
    //    redisTemplate.opsForZSet().remove(LocalDate.now().toString(),  map);
    //    map=new LinkedHashMap();
    //    map.clear();
    //    map.put("08:00",2);
    //    redisTemplate.opsForZSet().add(LocalDate.now().toString(),map,800);
    //
    //    return source;
    //}

}

